<template>
  <div class="cart-page">
    <div class="cart-header">
      <h1>购物车</h1>
      <div class="edit-btn" @click="isEditing = !isEditing">{{ isEditing ? '完成' : '编辑' }}</div>
    </div>
    
    <div v-if="loading" class="loading-indicator">
      正在加载数据...
    </div>
    
    <div v-else-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-else-if="cartItems.length > 0" class="cart-content">
      <div class="cart-items">
        <div class="cart-item" v-for="(item, index) in cartItems" :key="item._id || index">
          <div class="item-select">
            <div 
              class="checkbox" 
              :class="{ selected: item.selected }" 
              @click="toggleSelect(item)"
            ></div>
          </div>
          
          <div class="item-image">
            <img :src="item.image || `https://via.placeholder.com/80x80?text=${item.name}`" :alt="item.name" />
          </div>
          
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-spec">{{ item.spec || '默认规格' }}</div>
            <div class="item-price-quantity">
              <div class="item-price">¥{{ item.price }}</div>
              
              <div class="quantity-control">
                <button class="quantity-btn decrease" @click="decreaseQuantity(item)">-</button>
                <input type="number" v-model="item.quantity" class="quantity-input" />
                <button class="quantity-btn increase" @click="increaseQuantity(item)">+</button>
              </div>
            </div>
          </div>
          
          <div v-if="isEditing" class="delete-btn" @click="removeItem(index)">
            <div class="delete-icon"></div>
          </div>
        </div>
      </div>
      
      <div class="recommended">
        <h3 class="section-title">猜你喜欢</h3>
        <div class="recommended-items">
          <div 
            class="recommended-item" 
            v-for="(item, index) in recommendedItems" 
            :key="item._id || index"
            @click="addToCart(item)"
          >
            <div class="recommended-image">
              <img :src="item.image || `https://via.placeholder.com/100x100?text=${item.name}`" :alt="item.name" />
            </div>
            <div class="recommended-name">{{ item.name }}</div>
            <div class="recommended-price">¥{{ item.price }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="empty-cart">
      <div class="empty-cart-icon"></div>
      <div class="empty-cart-text">购物车还是空的</div>
      <div class="go-shopping-btn" @click="$router.push('/')">去逛逛</div>
    </div>
    
    <div v-if="cartItems.length > 0" class="cart-footer">
      <div class="select-all">
        <div 
          class="checkbox" 
          :class="{ selected: isAllSelected }" 
          @click="toggleSelectAll"
        ></div>
        <span>全选</span>
      </div>
      
      <div class="total-section">
        <div class="total-price">
          合计: <span class="price">¥{{ totalPrice }}</span>
        </div>
        <div class="checkout-btn" @click="checkout">结算 ({{ selectedCount }})</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { productAPI } from '../utils/api';

const isEditing = ref(false);
const loading = ref(false);
const error = ref('');

// 购物车项
const cartItems = ref<any[]>([]);

// 推荐商品
const recommendedItems = ref<any[]>([]);

// 从本地存储加载购物车数据
const loadCartFromStorage = () => {
  const cartData = localStorage.getItem('cart');
  if (cartData) {
    try {
      const parsedData = JSON.parse(cartData);
      cartItems.value = parsedData;
    } catch (err) {
      console.error('Failed to parse cart data from localStorage:', err);
      cartItems.value = [];
    }
  }
};

// 保存购物车到本地存储
const saveCartToStorage = () => {
  localStorage.setItem('cart', JSON.stringify(cartItems.value));
};

// 获取推荐商品
const fetchRecommendedProducts = async () => {
  loading.value = true;
  try {
    const response = await productAPI.getAll();
    // 只显示4个推荐商品
    recommendedItems.value = (response.data || []).slice(0, 4);
    
    // 如果没有数据，使用默认数据
    if (recommendedItems.value.length === 0) {
      recommendedItems.value = [
        {
          name: '休闲裤男士',
          price: '129.00',
          image: 'https://via.placeholder.com/100x100?text=Pants'
        },
        {
          name: '女士手提包',
          price: '239.00',
          image: 'https://via.placeholder.com/100x100?text=Bag'
        },
        {
          name: '运动鞋',
          price: '359.00',
          image: 'https://via.placeholder.com/100x100?text=Sneakers'
        },
        {
          name: '时尚墨镜',
          price: '99.00',
          image: 'https://via.placeholder.com/100x100?text=Glasses'
        }
      ];
    }
  } catch (err: any) {
    console.error('Error fetching recommended products:', err);
    error.value = err.message || '获取推荐商品失败';
    
    // 使用默认数据
    recommendedItems.value = [
      {
        name: '休闲裤男士',
        price: '129.00',
        image: 'https://via.placeholder.com/100x100?text=Pants'
      },
      {
        name: '女士手提包',
        price: '239.00',
        image: 'https://via.placeholder.com/100x100?text=Bag'
      },
      {
        name: '运动鞋',
        price: '359.00',
        image: 'https://via.placeholder.com/100x100?text=Sneakers'
      },
      {
        name: '时尚墨镜',
        price: '99.00',
        image: 'https://via.placeholder.com/100x100?text=Glasses'
      }
    ];
  } finally {
    loading.value = false;
  }
};

// 计算属性: 是否全选
const isAllSelected = computed(() => {
  return cartItems.value.length > 0 && cartItems.value.every(item => item.selected);
});

// 计算属性: 已选商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length;
});

// 计算属性: 总价
const totalPrice = computed(() => {
  const total = cartItems.value
    .filter(item => item.selected)
    .reduce((sum, item) => {
      return sum + parseFloat(item.price) * item.quantity;
    }, 0);
  return total.toFixed(2);
});

// 方法: 切换选中状态
const toggleSelect = (item: any) => {
  item.selected = !item.selected;
  saveCartToStorage();
};

// 方法: 切换全选状态
const toggleSelectAll = () => {
  const newState = !isAllSelected.value;
  cartItems.value.forEach(item => {
    item.selected = newState;
  });
  saveCartToStorage();
};

// 方法: 增加商品数量
const increaseQuantity = (item: any) => {
  if (item.quantity < 99) {
    item.quantity++;
    saveCartToStorage();
  }
};

// 方法: 减少商品数量
const decreaseQuantity = (item: any) => {
  if (item.quantity > 1) {
    item.quantity--;
    saveCartToStorage();
  }
};

// 方法: 删除商品
const removeItem = (index: number) => {
  cartItems.value.splice(index, 1);
  saveCartToStorage();
};

// 添加商品到购物车
const addToCart = (product: any) => {
  // 检查商品是否已在购物车中
  const existingItem = cartItems.value.find(item => item._id === product._id);
  
  if (existingItem) {
    // 如果商品已存在，增加数量
    existingItem.quantity++;
  } else {
    // 否则添加新商品
    cartItems.value.push({
      ...product,
      quantity: 1,
      selected: true
    });
  }
  
  saveCartToStorage();
};

// 结算方法
const checkout = () => {
  const selectedItems = cartItems.value.filter(item => item.selected);
  if (selectedItems.length === 0) {
    alert('请选择要结算的商品');
    return;
  }
  
  console.log('结算商品:', selectedItems);
  alert('订单提交成功！');
  
  // 移除已结算的商品
  cartItems.value = cartItems.value.filter(item => !item.selected);
  saveCartToStorage();
};

// 组件挂载时，加载购物车数据和推荐商品
onMounted(() => {
  loadCartFromStorage();
  fetchRecommendedProducts();
});
</script>

<style scoped>
.loading-indicator {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error-message {
  text-align: center;
  padding: 20px;
  color: #ff0000;
  background-color: #ffeeee;
  margin: 10px;
  border-radius: 4px;
}

.cart-page {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 50px);
  background-color: #f5f5f5;
  padding-bottom: 60px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.cart-header h1 {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.edit-btn {
  font-size: 14px;
  color: #666;
}

.cart-content {
  flex: 1;
  overflow-y: auto;
}

.cart-items {
  background-color: #fff;
  margin-bottom: 10px;
}

.cart-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.item-select {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.checkbox {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
}

.checkbox.selected {
  background-color: #ff6b35;
  border-color: #ff6b35;
  position: relative;
}

.checkbox.selected::after {
  content: '';
  width: 6px;
  height: 10px;
  border-right: 2px solid #fff;
  border-bottom: 2px solid #fff;
  transform: rotate(45deg) translate(-1px, -1px);
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  overflow: hidden;
}

.item-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-spec {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.item-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  font-size: 16px;
  color: #ff6b35;
  font-weight: bold;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 24px;
  height: 24px;
  border: 1px solid #ddd;
  background-color: #f8f8f8;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #666;
  padding: 0;
}

.quantity-btn.decrease {
  border-radius: 4px 0 0 4px;
}

.quantity-btn.increase {
  border-radius: 0 4px 4px 0;
}

.quantity-input {
  width: 36px;
  height: 24px;
  border: 1px solid #ddd;
  border-left: none;
  border-right: none;
  text-align: center;
  font-size: 14px;
  -moz-appearance: textfield;
}

.quantity-input::-webkit-inner-spin-button,
.quantity-input::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.delete-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-icon {
  width: 16px;
  height: 16px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23999' d='M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z'/%3E%3C/svg%3E");
  background-size: contain;
}

.recommended {
  background-color: #fff;
  padding-bottom: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  padding: 15px;
  margin: 0;
  border-bottom: 1px solid #eee;
}

.recommended-items {
  display: flex;
  overflow-x: auto;
  padding: 10px;
}

.recommended-item {
  width: 120px;
  flex-shrink: 0;
  margin-right: 10px;
  cursor: pointer;
}

.recommended-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 5px;
}

.recommended-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.recommended-name {
  font-size: 12px;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 36px;
}

.recommended-price {
  font-size: 14px;
  color: #ff6b35;
  font-weight: bold;
}

.empty-cart {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.empty-cart-icon {
  width: 80px;
  height: 80px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23ddd' d='M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z'/%3E%3C/svg%3E");
  background-size: contain;
  margin-bottom: 15px;
  opacity: 0.5;
}

.empty-cart-text {
  font-size: 16px;
  color: #999;
  margin-bottom: 15px;
}

.go-shopping-btn {
  padding: 8px 20px;
  background-color: #ff6b35;
  color: #fff;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}

.cart-footer {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fff;
  display: flex;
  align-items: center;
  border-top: 1px solid #eee;
  padding: 0 15px;
  z-index: 10;
}

.select-all {
  display: flex;
  align-items: center;
}

.select-all span {
  margin-left: 10px;
  font-size: 14px;
}

.total-section {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.total-price {
  margin-right: 15px;
  font-size: 14px;
}

.price {
  font-size: 18px;
  color: #ff6b35;
  font-weight: bold;
}

.checkout-btn {
  padding: 6px 20px;
  background-color: #ff6b35;
  color: #fff;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}
</style> 